package com.xwq.smartgelleryhub.model.dto.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.xwq.smartgelleryhub.model.entity.Space;
import com.xwq.smartgelleryhub.service.SpaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 空间Excel导入监听器
 */
@Slf4j
public class SpaceImportListener extends AnalysisEventListener<ExcelSpaceDTO> {

    /**
     * 批量处理的阈值
     */
    private static final int BATCH_COUNT = 100;
    
    /**
     * 缓存的数据列表
     */
    private List<Space> spaceList = new ArrayList<>();
    
    /**
     * 空间服务
     */
    private final SpaceService spaceService;
    
    /**
     * 成功导入的数量
     */
    private int successCount = 0;
    
    /**
     * 失败导入的数量
     */
    private int failCount = 0;
    
    public SpaceImportListener(SpaceService spaceService) {
        this.spaceService = spaceService;
    }
    
    @Override
    public void invoke(ExcelSpaceDTO data, AnalysisContext context) {
        log.info("解析到一条数据: {}", data);
        Space space = new Space();
        BeanUtils.copyProperties(data, space);
        spaceList.add(space);
        
        // 达到BATCH_COUNT，需要批量处理一次，防止数据几万条数据在内存，容易OOM
        if (spaceList.size() >= BATCH_COUNT) {
            saveData();
            // 清理list
            spaceList.clear();
        }
    }
    
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 确保最后遗留的数据也被保存
        saveData();
        log.info("所有数据解析完成！成功导入: {}条, 失败: {}条", successCount, failCount);
    }
    
    /**
     * 保存数据到数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储到数据库！", spaceList.size());
        try {
            for (Space space : spaceList) {
                try {
                    boolean success = spaceService.save(space);
                    if (success) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    log.error("保存空间数据失败: {}", e.getMessage(), e);
                    failCount++;
                }
            }
        } catch (Exception e) {
            log.error("批量保存空间数据异常: {}", e.getMessage(), e);
        }
        log.info("存储数据库成功！");
    }
    
    public int getSuccessCount() {
        return successCount;
    }
    
    public int getFailCount() {
        return failCount;
    }
} 